import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Spin, Badge, message, Drawer, Col, Row, Button, Modal } from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { ProductType } from '../../model';
import { Table } from 'antd';
import { myOrderData, orderDetailDataById, modifyOrder, changeOrder, orderProcessById } from './service';
import UpDownLabel from '../../components/Common/UpDownLabel';
import { manufacturerOption,moneyFormat, moneyFormat2,accAdd,accSub,accMul,productPropertyOption, priceOption } from '@/utils/utils';

import OrderInfo from '@/components/Common/OrderInfo'
import OrderHistory from '@/components/Common/OrderHistory'

import html2canvas from 'html2canvas';
import { Popconfirm } from 'antd';

class Order extends React.Component {
  actionRef = React.createRef<ActionType>();
  formRef = React.createRef<ActionType>();
  orderRef:any = React.createRef();
  orderHistoryRef:any = React.createRef();

  state = {
    activeKey: 'tab0',
    proModalVisible: false,
    detailFlag: false,
    sentArray: [],
    spinningFlag: false,
    dealerCode: '',
    editFlag: false,
    newDataSource: [],
    sentList: [],
    giftFlag: false,
    unitPrice: 0,
    sentPrice: 0,
    initData: {},
    auditFlag: false,
    auditData: [],
    modalVisible:false,
  };
  renderBadge = (count: number, active = false) => {
    return <Badge count={count} style={{
      marginTop: -2,
      marginLeft: 4,
      color: active ? '#1890FF' : '#999',
      backgroundColor: active ? '#E6F7FF' : '#eee'
    }}/>;
  };

  getButton = (record:any) =>{
    var btn = []
    btn.push(<a key='show' onClick={() => {this.orderRef.current.init('id')}}>详情</a>)
    btn.push(<a key='show' onClick={() => this.auditing(record)}>审核记录</a>)
    if(record.status ==5 && sessionStorage.getItem('access') == 'checker'){
      btn.push(<Popconfirm title='确定消退吗?' key='priceBtn' onConfirm={async () => this.destoryOrder(record)}>
      <a key='destory'>消退</a>
      </Popconfirm>)
    }

    return btn
  }
  columns: ProColumns[] = [{
    title: '订单号',
    width: 180,
    ellipsis:true,
    dataIndex: 'order_number',
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    },
  }, {
    title: '客户代码',
    dataIndex: 'dealerCode',
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    },
    width: 100
  }, {
    title: '客户名称',
    dataIndex: 'dealerName',
    width: 200,
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    },
    ellipsis: true
  }, {
    title: '状态',
    dataIndex: 'status',
    hideInSearch: true,
    valueType: 'select',
    width: 80,
    valueEnum: {
      2: {
        text: '待审核'
      },
      3: {
        text: '未通过'
      },
      4: {
        text: '待付款'
      },
      5: {
        text: '待发货'
      },
      6: {
        text: '待收货'
      },
      7: {
        text: '已完成'
      },
      8: {
        text: '已消退'
      }
    }
  }, {
    title: '实付金额',
    valueType: 'money',
    width: 150,
    dataIndex: 'actual_amount',
    hideInSearch: true
  }, {
    title: '订货日期',
    dataIndex: 'order_time',
    hideInSearch: true,
    width: 120
  }, // {
  //   title: '交货日期',
  //   dataIndex: 'delivery_time',
  //   hideInSearch:true,
  // },
  {
    title: '备注',
    dataIndex: 'remarks',
    ellipsis: true,
    width: 150,
    hideInSearch: true
  }, {
    title: '订货日期',
    valueType: 'dateRange',
    dataIndex: 'date',
    hideInTable: true
  }, {
    title: '审核日期',
    valueType: 'dateRange',
    dataIndex: 'approvalDate',
    hideInTable: true
  }, {
    title: '审核日期',
    dataIndex: 'approval_time',
    width: 120,
    hideInSearch: true
  }, {
    title: '操作',
    key: 'option',
    width: 150,
    valueType: 'option',
    fixed: 'right',
    render: (_, record) => this.getButton(record)
  }];
  auditColumn: ProColumns[] = [{
    title: '审核人员',
    dataIndex: 'userName',
    ellipsis: true,
    width: 200
  }, {
    title: '审核日期',
    dataIndex: 'approvaTime',
    width: 200,
    renderText: (_, record: any) => {
      if (record.approvaTime) {
        return record.approvaTime;
      }

      return record.applyTime;
    }
  }, {
    title: '操作状态',
    width: 100,
    dataIndex: 'isPass',
    renderText: (_, record: any) => {
      if (record.stepName === 'place') {
        return '下单';
      }
      if (record.stepName === 'place2') {
        return '修改订单';
      }

      if (record.stepName === 'warehouse') {
        return '发货';
      }

      if (record.isPass === '1') {
        return '通过';
      }

      if (record.isPass === '0') {
        return '待办理';
      } else {
        return '退回';
      }
    }
  }, {
    title: '审核意见',
    dataIndex: 'opinion'
  }];
  editSendColumns: ProColumns<ProductType>[] = [{
    title: '产品名称',
    dataIndex: 'product_name',
    ellipsis: true,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    },
    width: 200
  }, {
    title: '产品型号',
    // ellipsis: true,
    dataIndex: 'product_standard',
    width: 200
  }, {
    title: '单位',
    dataIndex: 'packing_unit',
    width: 60,
    ellipsis:true,
  }, {
    title: '订货数量',
    dataIndex: 'numbs',
    width: 70
  }, {
    title: '单价(元)',
    dataIndex: 'standard_price',
    width: 160,
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      if (record.unit_price && Number(record.unit_price) != Number(record.standard_price)) {
        return <>{moneyFormat(record.standard_price)}<span style={{
            textDecoration: 'line-through',
            color: '#d1d1d1',
            marginLeft: 10
          }}>{moneyFormat(record.unit_price)}</span></>;
      }

      return moneyFormat(record.standard_price);
    }
  }, {
    title: '已发货',
    dataIndex: 'send_numbs',
    width: 60
  }, {
    title: '金额(元)',
    dataIndex: 'actual_amount',
    width: 120,
    align: 'left',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `0`;
      }

      return moneyFormat(accMul(Number(record.standard_price), record.send_numbs));
    }
  }];

  auditing = async (record: any) => {
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id
    };
    var val = await orderProcessById(param);

    if (val.errorCode === '200') {
      val.data.push({"userName":'合肥**医疗科技有限公司',approvaTime:'2022-09-04 09:21:16',stepName:'place2'})
      this.setState({
        auditFlag: true,
        auditData: val.data
      });
    } else {
      message.error('获取订单审核记录失败');
    }

    this.setState({
      spinningFlag: false
    });
  };
  destoryOrder = async (record: any) => {
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id,
      'status': '8'
    };
    var val = await changeOrder(param);

    if (val.errorCode === '200') {
      this.actionRef.current?.reloadAndRest?.();
    } else {
      message.error(val.errorMessage);
    }

    this.setState({
      spinningFlag: false
    });
  };
  handlePreview = async (file: any) => {
    window.open(file.url);
  };
  printOrder = () => {
    const el: any = document.getElementById('billDetails');
    var scrollTop = document.documentElement.scrollTop;
    document.documentElement.scrollTop = 0;
    const win: any = window.open('', 'printwindow');
    html2canvas(el, {
      useCORS: true
    }).then(canvas => {
      win.document.body.appendChild(canvas);
      win.print();
      win.close();
      document.documentElement.scrollTop = scrollTop;
    });
  };
  
  render() {
   
    return <PageContainer>
    <ProTable actionRef={this.actionRef} formRef={this.formRef} columns={this.columns} scroll={{
        x: 1300
      }} request={(params, sorter, filter) => {
        // 表单搜索项会从 params 传入，传递给后端接口。
        // console.log(params, sorter, filter);
        var status = {
          status:'' 
        };

        if (this.state.activeKey === 'tab0') {
          status.status = '2,4,5,6,7';
        } else if (this.state.activeKey === 'tab1') {
          status.status = '2';
        } else if (this.state.activeKey === 'tab2') {
          status.status = '4';
        } else if (this.state.activeKey === 'tab3') {
          status.status = '5';
        } else if (this.state.activeKey === 'tab4') {
          status.status = '6';
        } else if (this.state.activeKey === 'tab5') {
          status.status = '7';
        } else if (this.state.activeKey === 'tab6') {
          status.status = '3';
        } else if (this.state.activeKey === 'tab7') {
          status.status = '8';
        }

        if (params.date) {
          params.beginDate = params.date[0];
          params.endDate = params.date[1];
          params.date = undefined;
        }

        if (params.approvalDate) {
          params.approvalBeginDate = params.approvalDate[0];
          params.approvalEndDate = params.approvalDate[1];
          params.approvalDate = undefined;
        }

        return myOrderData({ ...params,
          filter,
          ...status
        });
      }} search={{
        span: 6,
        defaultCollapsed: false,
        optionRender: ({
          searchText,
          resetText
        }, {
          form
        }) => [<Button key='search' type='primary' onClick={() => {
          form?.submit();
        }}>
            {searchText}
          </Button>, <Button key='rest' onClick={() => {
          form?.resetFields();
          form?.submit();
        }}>
            {resetText}
          </Button>]
      }} toolbar={{
        menu: {
          type: 'tab',
          activeKey: this.state.activeKey,
          items: [{
            key: 'tab0',
            label: <span>全部{this.renderBadge(0, this.state.activeKey === 'tab0')}</span>
          }, {
            key: 'tab1',
            label: <span>待审核{this.renderBadge(0, this.state.activeKey === 'tab1')}</span>
          }, {
            key: 'tab2',
            label: <span>待付款{this.renderBadge(0, this.state.activeKey === 'tab2')}</span>
          }, {
            key: 'tab3',
            label: <span>待发货{this.renderBadge(0, this.state.activeKey === 'tab3')}</span>
          }, {
            key: 'tab4',
            label: <span>待收货{this.renderBadge(0, this.state.activeKey === 'tab4')}</span>
          }, {
            key: 'tab5',
            label: <span>已完成{this.renderBadge(0, this.state.activeKey === 'tab5')}</span>
          }, {
            key: 'tab6',
            label: <span>未通过{this.renderBadge(0, this.state.activeKey === 'tab6')}</span>
          }, {
            key: 'tab7',
            label: <span>已消退{this.renderBadge(0, this.state.activeKey === 'tab7')}</span>
          }],
          onChange: key => {
            this.setState({
              activeKey: (key as string)
            });
            this.actionRef.current?.reloadAndRest?.();
          }
        },
        settings: [],
        actions: undefined
      }} rowKey='id' pagination={{
        pageSizeOptions: ['20', '100', '500']
      }} dateFormatter='string'/>

      <Drawer destroyOnClose={true} width={1200} title={'审核记录'} visible={this.state.auditFlag} onClose={() => {
        this.setState({
          auditFlag: false
        });
      }}>
          <ProTable<ProductType> headerTitle='' size='small' toolbar={{
          settings: []
        }} columns={this.auditColumn} dataSource={this.state.auditData} rowKey='id' pagination={false} search={false}>
          </ProTable>

        </Drawer>
        <Spin spinning={this.state.spinningFlag} style={{
        transform: 'translate(-50%,-50%)',
        left: '50%',
        top: '50%',
        position: 'absolute'
      }}/>
      <OrderInfo  ref={this.orderRef}></OrderInfo>

      <Modal  title=""
        width={'90%'}
        footer={false}
        destroyOnClose={true}
        visible={this.state.modalVisible}
        onCancel={()=>{
            this.setState({modalVisible:false})
        }}
       >
          <OrderHistory  ref={this.orderHistoryRef}></OrderHistory>
       </Modal>
    </PageContainer>;
  }

}

export default Order;